/*
 * UpdateUserStatusServlet.java
 * 作用：管理员后台的用户状态更新控制器，负责处理封禁/解封指定用户的请求，并包含不能更改管理员自己的逻辑。
 */
package com.campustradingwall.controller.admin;

import com.campustradingwall.dao.UserDao;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admin/updateUserStatus")
public class UpdateUserStatusServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        String userIdStr = request.getParameter("userId");
        String status = request.getParameter("status");

        if (userIdStr == null || status == null || (!status.equals("active") && !status.equals("banned"))) {
            session.setAttribute("message", "无效的操作请求。");
            response.sendRedirect(request.getContextPath() + "/admin/users");
            return;
        }

        try {
            int userId = Integer.parseInt(userIdStr);
            if (currentUser.getId() == userId) {
                session.setAttribute("message", "您不能更改自己的账户状态。");
                response.sendRedirect(request.getContextPath() + "/admin/users");
                return;
            }

            UserDao userDao = new UserDao();
            userDao.updateUserStatus(userId, status);
            session.setAttribute("message", "用户状态已成功更新。");

        } catch (Exception e) {
            session.setAttribute("message", "更新用户状态时发生错误：" + e.getMessage());
        }

        response.sendRedirect(request.getContextPath() + "/admin/users");
    }
} 